package client;

import java.io.IOException;
import java.sql.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import Dao.FoodsDao;
import Dao.ItemDao;
import Dao.OrdersDao;
import Dao.UsersDao;
import Dao.Impl.FoodsDaoImpl;
import Dao.Impl.ItemDaoImpl;
import Dao.Impl.OrdersDaoImpl;
import Dao.Impl.UsersDaoImpl;

import com.google.gson.Gson;

import entity.Foods;
import entity.Item;
import entity.Menu;
import entity.Orders;
import entity.Users;

public class BuyCarServlet extends BaseServlet {

 /**
	 * 
	 */
	private static final long serialVersionUID = 7866926783066043791L;

	public void buyCarCommit(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String buycar = request.getParameter("buycar");
		Gson gson = new Gson();
		Menu menu = gson.fromJson(buycar,  Menu.class);
		Orders order = new Orders();
		order.setUser_no(menu.getUser_no());
		order.setDate(new Date(System.currentTimeMillis()));
		Random random = new Random();
		order.setOrder_no(Math.abs(random.nextInt()));
		OrdersDao ordersDao = new OrdersDaoImpl();
		int money = 0;
		FoodsDao foodDao = new FoodsDaoImpl();
		UsersDao userDao = new UsersDaoImpl();
		
		try {
			ordersDao.add(order);
			Map<Integer, Integer> foodMap = menu.getFoodMap();
			ItemDao itemDao = new ItemDaoImpl();
			for (int  food_no : foodMap.keySet()) {
				Foods food = foodDao.getFood(food_no);
				money += food.getFood_price() * foodMap.get(food_no);
				Item item = new Item();
				item.setItem_no(Math.abs(random.nextInt()));
				item.setFood_no(food_no);
				item.setOrder_no(order.getOrder_no());
				item.setMealNo(foodMap.get(food_no));
				itemDao.add(item);
			}
			Users user = new Users();
			user.setUser_no(menu.getUser_no());
			user = userDao.query(user);
			user.setUser_score(user.getUser_score() - money);
			userDao.update(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
	}
}
